"""
Case Type   : 故障&可靠性测试
Case Name   : 使用failover备升主后，在新的主节点使用新主节点dump文件恢复
Create At   : 2020/11/25
Owner       : @zou_jialiang0505328126
Description :
    1.停止主节点
    2.备升主
    3.在备节点上导出数据
    4.恢复新的主节点数据
    5.检查数据一致性
    6.恢复故障节点
    7.恢复新的主节点数据
    8.检查数据一致性
Expect      :
    1.停止成功
    2.备升主成功
    3.导出成功
    4.恢复成功
    5.数据一致
    6.启动成功
    7.恢复成功
    8.数据一致
History     :
    modified: 2020/12/14  modified by @wan005,修改恢复数据库为新创建数据库，防止恢复失败导致后续用例失败
    modified: 2021/01/08  modified by @wan005,物化视图不支持compression等参数，修改断言适配1.1.0版本
    modified: 2021/03/26  modified by @wan005,修改备份路径，规避磁盘满导致的用例失败
"""

import os
import unittest
import time
import sys
from yat.test import macro
from yat.test import Node

sys.path.append(sys.path[0] + "/../")
from testcase.utils.CommonSH import *
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class Basebackup(unittest.TestCase):
    commonshpri = CommonSH('PrimaryDbUser')
    commonshsta = CommonSH('Standby1DbUser')
    commonshsta2 = CommonSH('Standby2DbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Tools_Restore_Case035.py 开始执行------------')
        self.dbPrimaryDbUser = Node(node='PrimaryDbUser')
        self.dbPrimaryRoot = Node(node='PrimaryRoot')
        self.dbStandby1DbUser = Node(node='Standby1DbUser')
        self.dbStandby2DbUser = Node(node='Standby2DbUser')
        self.Constant = Constant()
        self.common = Common('PrimaryRoot')
        self.restore_file = os.path.join(
            os.path.dirname(macro.DB_INSTANCE_PATH),
            'dump_backup', 'tools_restore_case001.tar')
        self.sql_path = os.path.join(macro.DB_BACKUP_PATH, 'testscript')

        self.log.info('-------------------创建备份路径-----------------------------------')
        shell_cmd = f'rm -rf {os.path.dirname(self.restore_file)}; mkdir {os.path.dirname(self.restore_file)}'
        self.log.info(shell_cmd)
        result = self.dbStandby1DbUser.sh(shell_cmd).result()
        self.log.info(result)

        self.log.info('-----------------------生成预设数据-----------------------')
        result = self.common.scp_file(self.dbPrimaryDbUser, 'restore_data.sql', self.sql_path)
        self.log.info(result)
        sql_file_cmd = f'''
                                source {macro.DB_ENV_PATH};
                                gsql -d {self.dbPrimaryDbUser.db_name} -p {self.dbPrimaryDbUser.db_port}  -f {os.path.join(
            self.sql_path, 'restore_data.sql')}
                                '''
        self.log.info(sql_file_cmd)
        sql_bx_msg = self.dbPrimaryDbUser.sh(sql_file_cmd).result()
        self.log.info(sql_bx_msg)
        self.assertNotIn('ERROR', sql_bx_msg)

        self.table_list = self.commonshpri.executDbSql(r'\d')
        self.log.info(self.table_list)

        self.dbname = 'dbsys_restore_db'
        self.log.info("---------------------创建数据库--------------------")
        result = self.commonshpri.executDbSql(f'drop database if exists {self.dbname};create database {self.dbname};')
        self.log.info(result)
        self.assertIn(self.Constant.CREATE_DATABASE_SUCCESS_MSG, result)

    def test_basebackup(self):
        self.log.info('------------------1.停止主节点：成功-----------------------------')
        result = self.commonshpri.stopDbInstance()
        self.log.info(result)
        self.assertIn(self.Constant.GS_CTL_STOP_SUCCESS_MSG, result)

        self.log.info('------------------2.备升主：成功-----------------------------')
        result = self.commonshsta.executeGsctl('failover', self.Constant.FAILOVER_SUCCESS_MSG)
        self.assertTrue(result)
        result = self.commonshsta.exec_refresh_conf()
        self.assertTrue((result))

        self.log.info('------------------3.在备节点上导出数据:成功-----------------------------')
        result = self.commonshsta.dumpFile(filename=self.restore_file, get_detail=False)
        self.log.info(result)
        self.assertTrue(result)
        time.sleep(10)

        self.log.info('------------------4.恢复新的主节点数据：成功-----------------------------')
        result = self.commonshsta.restoreFile(self.restore_file,'-c', True, self.dbname)
        self.assertIn(self.Constant.RESTORE_SUCCESS_MSG, result)

        self.log.info('------------------5.检查数据一致性：成功----------------------------')
        self.log.info('======对比恢复前后数据是否一致============')
        time.sleep(5)
        self.table_list_after = self.commonshsta.executDbSql(r'\d', dbname=self.dbname)
        self.log.info(self.table_list_after)
        self.assertIn(self.table_list, self.table_list_after)

        self.log.info('======检查主备是否同步======')
        result = self.commonshsta2.check_data_consistency()
        self.assertTrue(result)

        self.log.info('======检查数据一致性======')
        nodes_tuple = (self.dbStandby1DbUser, self.dbStandby2DbUser)
        flag = self.common.check_data_sample_by_all(r'\d', *nodes_tuple)
        self.assertTrue(flag)

        table_dict = self.common.format_sql_result(self.commonshsta.executDbSql(r'\d'))
        table_name = table_dict.get('Name')
        for name in table_name:
            select_sql = f'select count(*) from {name};'
            flag = self.common.check_data_sample_by_all(select_sql, *nodes_tuple)
            self.assertTrue(flag)

        self.log.info('------------------6.恢复故障节点------------------------')
        result = self.commonshpri.startDbInstance('standby')
        self.log.info(result)
        self.assertIn(self.Constant.RESTART_SUCCESS_MSG, result)

        self.log.info('------------------7.恢复新的主节点数据:成功------------------------')
        result = self.commonshsta.restoreFile(self.restore_file,'-c', True, self.dbname)
        self.assertIn(self.Constant.RESTORE_SUCCESS_MSG, result)

        self.log.info('------------------8.检查数据一致性------------------------')
        self.log.info('======对比恢复前后数据是否一致============')
        time.sleep(5)
        self.table_list_after = self.commonshpri.executDbSql(r'\d')
        self.log.info(self.table_list_after)
        self.assertIn(self.table_list, self.table_list_after)

        self.log.info('======检查主备是否同步======')
        result = self.commonshsta.check_data_consistency()
        self.assertTrue(result)
        result = self.commonshsta2.check_data_consistency()
        self.assertTrue(result)

        self.log.info('======检查数据一致性======')
        nodes_tuple = (self.dbPrimaryDbUser, self.dbStandby1DbUser, self.dbStandby2DbUser)
        flag = self.common.check_data_sample_by_all(r'\d', *nodes_tuple)
        self.assertTrue(flag)

        table_dict = self.common.format_sql_result(self.commonshpri.executDbSql(r'\d'))
        table_name = table_dict.get('Name')
        for name in table_name:
            select_sql = f'select count(*) from {name};'
            flag = self.common.check_data_sample_by_all(select_sql, *nodes_tuple)
            self.assertTrue(flag)

    def tearDown(self):
        self.log.info('-------------------------环境清理------------------------')
        self.log.info('--------------------------删除备份文件------------------')
        shell_cmd = f'rm -rf {os.path.dirname(self.restore_file)}'
        self.log.info(shell_cmd)
        result = self.dbStandby1DbUser.sh(shell_cmd).result()
        self.log.info(result)

        self.log.info('-----------------------------恢复主备关系-----------------')
        host_name = self.dbPrimaryRoot.sh('hostname').result()
        result = self.commonshpri.check_whether_need_switch(host_name)
        if result:
            result = self.commonshpri.startDbInstance('standby')
            self.log.info(result)
            result = self.commonshpri.executeGsctl('switchover', self.Constant.SWITCHOVER_SUCCESS_MSG)
            self.log.info(result)
            result = self.commonshpri.exec_refresh_conf()
            self.log.info(result)

        self.log.info('--------------------------删除预设数据---------------------')
        result = self.common.scp_file(self.dbPrimaryDbUser, 'clear_restore_data.sql', self.sql_path)
        self.log.info(result)
        sql_file_cmd = f'''
                            source {macro.DB_ENV_PATH};
                            gsql -d {self.dbPrimaryDbUser.db_name} -p {self.dbPrimaryDbUser.db_port}  -f {os.path.join(
            self.sql_path, 'clear_restore_data.sql')}'''
        self.log.info(sql_file_cmd)
        sql_bx_msg = self.dbPrimaryDbUser.sh(sql_file_cmd).result()
        self.log.info(sql_bx_msg)

        self.log.info('----------------------删除执行脚本路径----------------------------')
        shell_cmd = f'rm -rf {self.sql_path}'
        self.log.info(shell_cmd)
        result = self.dbPrimaryDbUser.sh(shell_cmd).result()
        self.log.info(result)

        self.log.info("---------------------drop database--------------------")
        result = self.commonshpri.executDbSql(f'drop database {self.dbname};')
        self.log.info(result)
        self.log.info('----------Opengauss_Reliability_Tools_Restore_Case035.py 执行结束-----------------------')
